package com.jdrx.sw.sewage.service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jdrx.platform.commons.rest.beans.vo.ResponseVO;
import com.jdrx.platform.commons.rest.exception.BizException;
import com.jdrx.platform.commons.rest.factory.ResponseFactory2;
import com.jdrx.sw.sewage.beans.dto.*;
import com.jdrx.sw.sewage.beans.dto.base.PageDTO;
import com.jdrx.sw.sewage.beans.entity.DevStoragePO;
import com.jdrx.sw.sewage.beans.entity.WorkOrderPO;
import com.jdrx.sw.sewage.beans.vo.*;
import com.jdrx.sw.sewage.beans.vo.base.PageVO;
import com.jdrx.sw.sewage.dao.DevStorageDAO;
import com.jdrx.sw.sewage.dao.DeviceDAO;
import com.jdrx.sw.sewage.dao.WorkOrderDAO;
import com.jdrx.sw.sewage.service.base.BaseServiceImpl;
import com.jdrx.sw.sewage.service.common.ExcleExportService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class MaintenanceServiceImpl extends BaseServiceImpl {

    public static final Logger logger = LoggerFactory.getLogger(MaintenanceServiceImpl.class);

    @Autowired
    private WorkOrderDAO workOrderDAO;
    @Autowired
    private ExcleExportService excleExportService;
    @Autowired
    private DeviceDAO deviceDAO;
    @Autowired
    private DevStorageDAO devStorageDAO;

    public PageVO<MaintenanceDevVO> findMaintenanceDevList(PageDTO pageDTO) {
        PageHelper.startPage(pageDTO);
        List<MaintenanceDevVO> maintenanceDevVOs = workOrderDAO.findMaintenanceDevList();
        return PageVO.toPageVO(maintenanceDevVOs);
    }

    public Map<String, Object> findNoDo(Long currUserId) {
        HashMap<String, Object> map = new HashMap();
        HashMap<String, Object> mapToday = new HashMap();
        HashMap<String, Object> mapFuture = new HashMap();

        mapToday.put("data", workOrderDAO.findTodayNoDo(currUserId, 1));
        mapFuture.put("data", workOrderDAO.findTodayNoDo(currUserId, 0));

        if (null == currUserId) map.put("total", workOrderDAO.countAll());
        else map.put("total", workOrderDAO.countTodayNoDo(currUserId, 0) + workOrderDAO.countTodayNoDo(currUserId, 1));


        map.put("today", mapToday);
        map.put("future", mapFuture);
        return map;
    }

    public Integer findNoDoNum(Long currUserId) {
        if (null == currUserId) return workOrderDAO.countAll();
        return workOrderDAO.countTodayNoDo(currUserId, 0) + workOrderDAO.countTodayNoDo(currUserId, 1);
    }

    public ResponseVO maintenanceApply(MaintenanceApplyDTO dto) throws BizException {
        WorkOrderPO workOrderPO = workOrderDAO.findIsNot(dto.getDevId(), dto.getType());
        if (null != workOrderPO) return ResponseFactory2.err("已存在未完成的工单");

        Map<String, Object> newWorkOrderPO = new HashMap<>();
        newWorkOrderPO.put("type", dto.getType());
        newWorkOrderPO.put("devId", dto.getDevId());
        newWorkOrderPO.put("maintenanceById", dto.getMaintenanceById());
        newWorkOrderPO.put("maintenanceBy", dto.getMaintenanceBy());
        newWorkOrderPO.put("singlePersonId", dto.getSinglePersonId());
        newWorkOrderPO.put("singlePerson", dto.getSinglePerson());
        newWorkOrderPO.put("maintenanceTime", "'" + dto.getMaintenanceTime() + "'");
        newWorkOrderPO.put("opinion", dto.getOpinion());
        newWorkOrderPO.put("faultDesc", dto.getFaultDesc());
        newWorkOrderPO.put("estimatedCost", dto.getEstimatedCost());
        newWorkOrderPO.put("createAt", "'" + new Date() + "'");
        newWorkOrderPO.put("status", 0);

        /*workOrderPO = new WorkOrderPO();
        BeanUtils.copyProperties(dto, workOrderPO);
        workOrderPO.setCreateAt(new Date());
        workOrderPO.setStatus(0);*/
        workOrderDAO.add(newWorkOrderPO);

        //标记保养已派单
        if (1 == dto.getType()) deviceDAO.updateDispatch(dto.getDevId(), 1);

        return ResponseFactory2.ok();
    }

    public void maintenance(MaintenanceUpdateDTO dto) {
        WorkOrderPO workOrderPO = new WorkOrderPO();
        BeanUtils.copyProperties(dto, workOrderPO);
        workOrderPO.setStatus(1);
        workOrderPO.setCompleteTime(new Date());
        workOrderDAO.update(workOrderPO);

        DevStoragePO po = deviceDAO.findByMaintenanceId(dto.getId());
        po.setCycleTime(po.getMaintenanceCycleDay());
        po.setWorkTime(po.getMaintenanceCycleHour());
        po.setInitWorkTime(0);
        devStorageDAO.updateDev(po);

        WorkOrderPO byId = workOrderDAO.findById(dto.getId());
        deviceDAO.updateDispatch(byId.getDevId(), 0);
    }

    public void dispatch(DispatchDTO dto) {
        Map<String, Object> workOrderPO = new HashMap<>();
        workOrderPO.put("type", dto.getType());
        workOrderPO.put("devId", dto.getDevId());
        workOrderPO.put("maintenanceById", dto.getMaintenanceById());
        workOrderPO.put("maintenanceBy", dto.getMaintenanceBy());
        workOrderPO.put("singlePersonId", dto.getSinglePersonId());
        workOrderPO.put("singlePerson", dto.getSinglePerson());
        workOrderPO.put("maintenanceTime", "'" + dto.getMaintenanceTime() + "'");
        workOrderPO.put("createAt", "'" + new Date() + "'");
        workOrderPO.put("status", 0);

        /*WorkOrderPO workOrderPO = new WorkOrderPO();
        BeanUtils.copyProperties(dto, workOrderPO);
        workOrderPO.setCreateAt(new Date());
        workOrderPO.setStatus(0);*/
        workOrderDAO.add(workOrderPO);
        //标记已派单
        deviceDAO.updateDispatch(dto.getDevId(), 1);
    }

    public PageVO<MaintenanceRecordVO> findMaintenanceRecordList(MaintenanceRecordDTO dto) {
        PageHelper.startPage(dto);
        List<MaintenanceRecordVO> maintenanceDevVOs = workOrderDAO.findMaintenanceRecordList(dto);
        return PageVO.toPageVO(maintenanceDevVOs);
    }

    public List<MaintenanceRecordVO> findMaintenanceRecordLists(Integer type, Long devId) {
        return workOrderDAO.findMaintenanceRecordLists(type, devId);
    }

    public List<FactoryPeriodsVO> findFactoryPeriods() {
        List<FactoryPeriodsVO> factoryPeriods = workOrderDAO.findFactoryPeriods();
        factoryPeriods.forEach(item -> {
            List<ProcessunitVO2> processunitByFp = workOrderDAO.findProcessunitByFp(item.getFactoryPeriod());
            item.setProcessunitVOs(processunitByFp);
            processunitByFp.forEach(item2 -> {
                item2.setCategoryVOs(workOrderDAO.findCategoryByPid(item2.getId()));
            });
        });
        return factoryPeriods;
    }

    public MaintenanceRecordInfoVO findMaintenanceRecordInfo(Long id) {
        return workOrderDAO.findMaintenanceRecordInfo(id);
    }

    public void exportMaintenanceRecord(HttpServletResponse response, MaintenanceRecordDTO2 dto) throws BizException {
        MaintenanceRecordDTO dto2 = new MaintenanceRecordDTO();
        BeanUtils.copyProperties(dto, dto2);
        List<MaintenanceRecordVO> maintenanceDevVOs = workOrderDAO.findMaintenanceRecordList(dto2);
        if (1 == dto.getType())
            excleExportService.generateExcel(response, maintenanceDevVOs, MaintenanceRecordExportVO.class, "保养记录");
        if (2 == dto.getType())
            excleExportService.generateExcel(response, maintenanceDevVOs, MaintenanceRecordExportVO2.class, "维修记录");
    }

    public List<MaintenanceDevVO> findUserMaintenance(UserMaintenanceDTO userMaintenanceDTO) {
        userMaintenanceDTO.setMaintenanceTime("'" + userMaintenanceDTO.getMaintenanceTime() + "'");
        return workOrderDAO.findUserMaintenance(userMaintenanceDTO);
    }

    /**
     * 获取未来 第 past 天的日期
     *
     * @param past
     * @return
     */
    public static String getFetureDate(int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + past);
        Date today = calendar.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result = format.format(today);
        return result;
    }

    public List findUserMaintenanceTime(Long maintenanceById) {
        List list = Lists.newArrayList();
        for (int i = 0; i < 7; i++) {
            String maintenanceTime = getFetureDate(i);
            JSONObject json = new JSONObject();
            json.put(maintenanceTime, workOrderDAO.countUserMaintenance(maintenanceById, "'" + maintenanceTime + "'"));
            list.add(json);
        }
        return list;
    }

    public List<MaintenanceDevVO> finMaintenanceDevByFp(String factoryPeriods, Long processunitId, Long categoryId, Integer type) {
        List<MaintenanceDevVO> maintenanceDevVOS = workOrderDAO.finMaintenanceDevByFp(factoryPeriods, processunitId, categoryId);
        maintenanceDevVOS.forEach(item -> {
            if (Objects.nonNull(workOrderDAO.findIsNot(item.getDevId(), type))) item.setNoWorkOrder(1);
        });
        return maintenanceDevVOS;
    }

    public Map<String, Integer> assetsMaintain(StationIdDTO dto) {
        Integer devTotal = deviceDAO.countDevTotalNum();
        Integer maintenanceDue = deviceDAO.countMaintenanceSevenDay(dto.getStationId(), null);
        Integer maintainNum = deviceDAO.countMaintenanceSevenDay(dto.getStationId(), 2);
        Double maintenanceDueThan = 0.0;
        Double maintainNumThan = 0.0;

        HashMap map = Maps.newHashMap();
        map.put("maintenanceDue", maintenanceDue);
        map.put("maintainNum", maintainNum);
        map.put("devTotal", devTotal);
        if (devTotal > 0) {
            maintenanceDueThan = Double.valueOf(maintenanceDue) / devTotal;
            maintainNumThan = Double.valueOf(maintainNum) / devTotal;
        }
        map.put("maintenanceDueThan", maintenanceDueThan);
        map.put("maintainNumThan", maintainNumThan);
        return map;
    }
}